<?php


namespace app\shop\controller\api\v1;


use app\common\controller\BaseApiController;
use app\common\model\ShopMember;
use app\common\model\ShopMemberExpire;
use app\common\model\ShopMemberMonths;
use app\common\model\ShopMemberMonthsRecord;

class TimeFree extends BaseApiController
{
    /**
     * 每月赠送免费洗衣次数
     */
    public function getNum()
    {
        $month = date('Y-m',time());
        $now_day = date('Y-m-d',time());
        $day = date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'));
        if ($now_day == $day){
            $info = ShopMemberMonths::where('month',$month)->find();
            if (!$info){
                $month_data = [
                    'month' => $month,
                    'num' => sysconf('free_wish_num')
                ];
                $month = ShopMemberMonths::create($month_data);
                if ($month){
                    $member_list = ShopMember::whereTime('expire_time', '>=', time())->where('status',1)->select();
                    if (!empty($member_list)){
                        $record_data = [];
                        $free_data = [];
                        foreach ($member_list as $key => $value){
                            $record_data[] = [
                                'month_id' => $month->id,
                                'member_id' => $value['id'],
                                'uid' => $value['uid']
                            ];
                            $free_data[] = [
                                'id' => $value['id'],
                                'free_num' => sysconf('free_wish_num'),
                                'free_use_num' => 0
                            ];
                        }
                        (new ShopMemberMonthsRecord())->saveAll($record_data);
                        (new ShopMember())->saveAll($free_data);
                    }
                }
            }
        }
        $this->successCode();
    }

}